package com.kindac.together.uitl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.kindac.together.R;
import com.kindac.together.common.Kin;
import com.kindac.together.db.KinDB;
import com.kindac.together.service.HeadService;

/**
 * @author Kindac
 * @time 2011-6-16 上午01:17:30
 */
public class Utils {

    /**
     * 退出
     * 
     * @param context
     */
    public static void exitApp(final Context context) {

        // 背景音乐
        try {
            context.startService(new Intent(Kin.curAct, HeadService.class).setAction(Kin.PAUSE));
        } catch (Exception e) {
        }

        final Dialog dialog = new Dialog(context, R.style.TANCStyle);
        dialog.setContentView(R.layout.dialog);
        // dialog.setTitle(context.getResources().getString(R.string.info));
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        dialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                context.startService(new Intent(Kin.curAct, HeadService.class).setAction(Kin.MUSIC));
            }
        });
        ImageButton btnCancel = (ImageButton) dialog.findViewById(R.id.btnResume);
        btnCancel.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View view) {
                dialog.cancel();
            }
        });
        ImageButton btnCance2 = (ImageButton) dialog.findViewById(R.id.btnQuit);
        btnCance2.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View view) {
                dialog.dismiss();
                killProcess(context);
            }
        });

        dialog.show();
    }

    public static void stopService(final Context context) {
        try {
            Intent i = new Intent(context, HeadService.class);
            context.stopService(i);
        } catch (Exception e) {
        }
    }

    /**
     * 自杀
     * 
     * @param context
     */
    public static void killProcess(final Context context) {

        stopService(context);

        new Thread() {

            public void run() {
                String packageName = context.getPackageName();
                String processId = "";
                try {
                    Runtime r = Runtime.getRuntime();
                    Process p = r.exec("ps");
                    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String inline;
                    while ((inline = br.readLine()) != null) {
                        if (inline.contains(packageName)) {
                            break;
                        }
                    }
                    br.close();
                    StringTokenizer processInfoTokenizer = new StringTokenizer(inline);
                    int count = 0;
                    while (processInfoTokenizer.hasMoreTokens()) {
                        count++;
                        processId = processInfoTokenizer.nextToken();
                        if (count == 2) {
                            break;
                        }
                    }
                    r.exec("kill -9 " + processId);
                } catch (IOException error) {
                    error.printStackTrace();
                }
            }
        }.start();

    }

    public static int getRandom(int size) {
        return (int) (Math.random() * size);
    }

    /**
     * 弹出提示信息
     * 
     * @param active
     * @param message
     */
    public static void MessageBox(Context context, String str) {

        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

    }

    public static void init(final Context context) throws Exception {

        // 看看配置
        KinDB db = KinDB.getInstance(context);
        HashMap<String, Integer> my = db.getConfig(context);

        // 每次打开自加一
        db.updateConfigs(context, 0, 0, 0, my.get("open") + 1, -1);

        // 这时候de说
        if (my.get("open") == Kin.lol - 1 && (my.get("known1") == 0 || my.get("known2") == 0)) {

            Kin.isWrite = true;
        }

        if (Kin.isWrite == false) {
            //
            // 不要写字 ，page 默认值2倍,让你看着萌萌的图片傻笑
            //
            Kin.page += Kin.page;
            createBitmap(context);
        } else {

            Kin.arrString1 = new Vector<String>();
            Kin.arrString2 = new Vector<String>();

            String content = "";
            // TODO:db支持
            if (my.get("post") != -1) {
                // 你聪明
                content = db.getOnePost(context, my.get("post"));

                if (content == null) {
                    // 可能数据库错误
                    db.saveConfig(context);
                    content = "";
                }

            } else if (my.get("known0") == 0 && my.get("open") == Kin.page) {

                content = context.getResources().getString(R.string.text_info_0);
            } else if (my.get("known1") == 0 && my.get("open") == Kin.lol - 1) {
                // 你太笨了, 如果你没进这里,我请你吃饭!!!
                content = context.getResources().getString(R.string.text_info_1);
            } else if (my.get("known2") == 0 && my.get("open") == Kin.lol * 2) {
                // 代考虑
                content = context.getResources().getString(R.string.text_info_2);
            } else {
                content = context.getResources().getString(R.string.text_demo);

            }

            String[] list = content.split(",");
            for (String temp : list) {

                if (temp == null) {
                    Kin.arrString1.add("");
                    Kin.arrString2.add("");
                    continue;
                }

                String[] ll = temp.split(" ");

                if (ll.length == 1) {
                    Kin.arrString1.add(ll[0]);
                    Kin.arrString2.add("");
                } else {
                    Kin.arrString1.add(ll[0]);
                    Kin.arrString2.add(ll[1]);
                }
            }

            Kin.page = Kin.page > Kin.arrString1.size() ? Kin.page : Kin.arrString1.size() + 1;

            createBitmap(context);
        }
    }

    /**
     * 加栽图片1
     */
    public static void createBitmap(final Context context) {
        Kin.bitMapCache = new HashMap<Integer, Bitmap>();

        Bitmap bt;
        Canvas canvas;
        // 本地缓存页面标记
        Vector<Integer> v = new Vector<Integer>();
        // 直接建立4张图片, 随机生成
        for (int i = 0; i < Kin.page; i++) {

            // 最后一张单独处理
            if (i == Kin.page - 1) {
                bt = createBitmap(context, Kin.last);
                canvas = new Canvas(bt);

                font(context, canvas, i, true);

                Kin.bitMapCache.put(i, bt);

                return;
            }

            // 随机取图片
            int j = getRandom(Kin.arrDrawble.length);

            if (v.contains(j)) {
                Log.i(Utils.class.getName(), " no drawble!!" + j);
                i--;
                continue;
            }
            v.add(j);

            bt = createBitmap(context, Kin.arrDrawble[j]);
            canvas = new Canvas(bt);

            font(context, canvas, i, j % 2 == 0);

            Kin.bitMapCache.put(i, bt);
        }
        v.clear();
        v = null;

    }

    /**
     * 写字
     * 
     * @throws InterruptedException
     */
    private static void font(final Context context, final Canvas canvas, final int num, final boolean is) {

        if (Kin.isWrite == false) return;

        Paint paint = new Paint();
        paint.setFlags(Paint.ANTI_ALIAS_FLAG); // 取锯齿
        paint.setAntiAlias(true);
        paint.setFakeBoldText(true);
        Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
        paint.setUnderlineText(true);
        paint.setTypeface(font);

        if (is) {
            paint.setColor(Color.MAGENTA);
        } else {
            paint.setColor(Color.BLACK);
        }

        FontMetrics fontMetrics = paint.getFontMetrics();
        int baseX = Kin.mWidth / 3;
        int baseY = Kin.mHeight / 2;

        String content1 = "";
        String content2 = "";
        try {
            content1 = Kin.arrString1.get(num);
            content2 = Kin.arrString2.get(num);
        } catch (Exception e) {
        }
        // TODO: 根据不同屏幕 不同坐标
        switch (Kin.disPlay) {

            case Kin.mini:

                if (num == Kin.page - 1) {
                    baseX -= 40;
                    baseY -= 60;

                    font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
                    paint.setTypeface(font);
                    paint.setTextSize(14);

                    canvas.drawText(context.getString(R.string.info_1), baseX, baseY, paint);
                    baseX += 50;
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_2), baseX, baseY, paint);
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_3), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_4), baseX, baseY, paint);
                    baseX += 40;
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_5), baseX, baseY, paint);
                    baseX += 50;
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_6), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 15;
                    canvas.drawText(context.getString(R.string.info_7), baseX, baseY, paint);

                    canvas.drawText("Play", Kin.mWidth - 80, Kin.mHeight - 20, paint);

                } else {

                    paint.setTextSize(18);

                    baseX -= 100;
                    baseY -= 40;
                    canvas.drawText(content1, baseX, baseY, paint);
                    baseX += 120;
                    baseY += fontMetrics.bottom + 60;
                    canvas.drawText(content2, baseX, baseY, paint);

                    paint.setTextSize(18);
                    canvas.drawText(num + "", Kin.mWidth - 30, Kin.mHeight - 20, paint);
                }

                break;
            case Kin.defalut:

                if (num == Kin.page - 1) {
                    baseX -= 40;
                    baseY -= 60;

                    font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
                    paint.setTypeface(font);
                    paint.setTextSize(22);

                    canvas.drawText(context.getString(R.string.info_1), baseX, baseY, paint);
                    baseX += 80;
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_2), baseX, baseY, paint);
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_3), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_4), baseX, baseY, paint);
                    baseX += 40;
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_5), baseX, baseY, paint);
                    baseX += 80;
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_6), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 20;
                    canvas.drawText(context.getString(R.string.info_7), baseX, baseY, paint);

                    canvas.drawText(context.getString(R.string.info_8), Kin.mWidth - 60, Kin.mHeight - 20, paint);

                } else {
                    // 字体大小
                    paint.setTextSize(26);

                    baseX -= 60;
                    baseY -= 40;
                    canvas.drawText(content1, baseX, baseY, paint);
                    baseX += 60;
                    baseY += fontMetrics.bottom + 100;
                    canvas.drawText(content2, baseX, baseY, paint);
                    paint.setTextSize(18);
                    canvas.drawText(num + "", Kin.mWidth - 30, Kin.mHeight - 20, paint);
                }
                break;
            case Kin.large:

                if (num == Kin.page - 1) {
                    baseX -= 40;
                    baseY -= 100;

                    font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
                    paint.setTypeface(font);
                    paint.setTextSize(32);

                    canvas.drawText(context.getString(R.string.info_1), baseX, baseY, paint);
                    baseX += 80;
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_2), baseX, baseY, paint);
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_3), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_4), baseX, baseY, paint);
                    baseX += 40;
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_5), baseX, baseY, paint);
                    baseX += 80;
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_6), baseX, baseY, paint);
                    baseX -= 60;
                    baseY += fontMetrics.bottom + 40;
                    canvas.drawText(context.getString(R.string.info_7), baseX, baseY, paint);

                    canvas.drawText("Play", Kin.mWidth - 80, Kin.mHeight - 20, paint);

                } else {

                    paint.setTextSize(42);

                    baseX -= 100;
                    baseY -= 40;
                    canvas.drawText(content1, baseX, baseY, paint);
                    baseX += 120;
                    baseY += fontMetrics.bottom + 120;
                    canvas.drawText(content2, baseX, baseY, paint);

                    paint.setTextSize(18);
                    canvas.drawText(num + "", Kin.mWidth - 30, Kin.mHeight - 20, paint);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 加栽图片2
     */
    private static Bitmap createBitmap(Context context, int rc) {

        Bitmap bt = Bitmap.createBitmap(Kin.mWidth, Kin.mHeight, Bitmap.Config.ARGB_8888);

        Drawable drawale = context.getResources().getDrawable(rc);
        // 图片画片
        Canvas cas = new Canvas(bt);
        drawale.setBounds(0, 0, Kin.mWidth, Kin.mHeight);
        // 图片加载到bitmap上
        drawale.draw(cas);
        return bt;
    }
}
